package com.gh.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gh.bo.TransFlowBO;
import com.gh.common.exception.Assert;
import com.gh.common.result.ResponseEnum;
import com.gh.entity.Lend;
import com.gh.entity.LendItem;
import com.gh.entity.LendItemReturn;
import com.gh.entity.LendReturn;
import com.gh.enums.LendStatusEnum;
import com.gh.enums.TransTypeEnum;
import com.gh.hfb.FormHelper;
import com.gh.hfb.HfbConst;
import com.gh.hfb.RequestHelper;
import com.gh.mapper.LendItemMapper;
import com.gh.mapper.LendReturnMapper;
import com.gh.mapper.UserAccountMapper;
import com.gh.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gh.util.LendNoUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 还款记录表 服务实现类
 * </p>
 *
 * @author Eric
 * @since 2021-09-06
 */
@Service
public class LendReturnServiceImpl extends ServiceImpl<LendReturnMapper, LendReturn> implements LendReturnService {

    @Autowired
    private LendService lendService;
    @Autowired
    private UserBindService userBindService;
    @Autowired
    private LendItemReturnService lendItemReturnService;
    @Autowired
    private UserAccountService userAccountService;
    @Autowired
    private UserAccountMapper userAccountMapper;
    @Autowired
    private TransFlowService transFlowService;
    @Autowired
    private LendItemMapper lendItemMapper;

    @Override
    public List<LendReturn> selectByLendId(Long lendId) {
        LambdaQueryWrapper<LendReturn> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LendReturn::getLendId, lendId);
        List<LendReturn> lendReturnList = baseMapper.selectList(queryWrapper);
        return lendReturnList;
    }

    @Override
    public String commitReturn(Long lendReturnId, Long userId) {
        //还款记录
        LendReturn lendReturn = baseMapper.selectById(lendReturnId);
        //获取用户余额
        BigDecimal account = userAccountService.getAccount(userId);
        Assert.isTrue(account.doubleValue() >= lendReturn.getTotal().doubleValue(), ResponseEnum.NOT_SUFFICIENT_FUNDS_ERROR);
        //标的信息
        Lend lend = lendService.getById(lendReturn.getLendId());

        Map<String, Object> map = new HashMap<>();
        map.put("agentId", HfbConst.AGENT_ID);
        map.put("agentGoodsName", lend.getTitle());
        map.put("agentBatchNo", lendReturn.getReturnNo());
        String bindCode = userBindService.getBindCodeByUserId(userId);
        //还款人绑定协议号
        map.put("fromBindCode", bindCode);
        //还款总额
        map.put("totalAmt", lendReturn.getTotal());
        map.put("note", "");
        //还款明细
        List<Map<String, Object>> lendItemReturnDetailList = lendItemReturnService.addReturnDetail(lendReturnId);
        map.put("data", JSONObject.toJSONString(lendItemReturnDetailList));
        map.put("voteFeeAmt", new BigDecimal(0));
        map.put("notifyUrl", HfbConst.BORROW_RETURN_NOTIFY_URL);
        map.put("returnUrl", HfbConst.BORROW_RETURN_RETURN_URL);
        map.put("timestamp", RequestHelper.getTimestamp());
        map.put("sign", RequestHelper.getSign(map));
        return FormHelper.buildForm(HfbConst.BORROW_RETURN_URL, map);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public String notifyUrl(Map<String, Object> map) {
        //幂等性判断
        String agentBatchNo = (String) map.get("agentBatchNo");
        boolean isSave = transFlowService.isSaveTransFlow(agentBatchNo);
        if (isSave) {
            return "success"; //幂等性返回
        }
        //获取还款数据
        LambdaQueryWrapper<LendReturn> queryWrapper = new QueryWrapper<LendReturn>().lambda().eq(LendReturn::getReturnNo, agentBatchNo);
        LendReturn lendReturn = baseMapper.selectOne(queryWrapper);
        //更新还款状态
        String voteFeeAmt = (String) map.get("voteFeeAmt");
        lendReturn.setFee(new BigDecimal(voteFeeAmt));
        lendReturn.setStatus(1);
        lendReturn.setRealReturnTime(new Date());
        baseMapper.updateById(lendReturn);
        //更新标的信息
        Lend lend = lendService.getById(lendReturn.getLendId());
        //如果是最后一次还款，就更新标的状态
        if (lendReturn.getLast()) {
            lend.setStatus(LendStatusEnum.PAY_OK.getStatus());
            lendService.updateById(lend);
        }
        //还款账户转出金额
        BigDecimal totalAmt = new BigDecimal((String) map.get("totalAmt"));
        String bindCode = userBindService.getBindCodeByUserId(lendReturn.getUserId());
        userAccountMapper.updateAccount(bindCode, totalAmt.negate(), new BigDecimal(0));
        //还款流水
        TransFlowBO transFlowBO = new TransFlowBO(
                agentBatchNo,
                bindCode,
                totalAmt,
                TransTypeEnum.RETURN_DOWN,
                "还款啦"
        );
        transFlowService.saveTransFlow(transFlowBO);
        //回款明细的获取
        List<LendItemReturn> lendItemReturnList = lendItemReturnService.selectLendItemReturnList(lendReturn.getId());
        lendItemReturnList.forEach(lendItemReturn -> {
            //回款状态更新
            lendItemReturn.setStatus(1);
            lendItemReturnService.updateById(lendItemReturn);
            //更新出借信息
            LendItem lendItem = lendItemMapper.selectById(lendItemReturn.getLendItemId());
            lendItem.setRealAmount(lendItem.getRealAmount().add(lendItemReturn.getInterest()));
            lendItemMapper.updateById(lendItem);
            //资金转入
            String investBindCode = userBindService.getBindCodeByUserId(lendItemReturn.getInvestUserId());
            userAccountMapper.updateAccount(investBindCode, lendItemReturn.getTotal(), new BigDecimal(0));
            //流水
            TransFlowBO transFlowBo = new TransFlowBO(
                    LendNoUtils.getReturnItemNo(),
                    investBindCode,
                    lendItemReturn.getTotal(),
                    TransTypeEnum.INVEST_BACK,
                    "回款啦"
            );
            transFlowService.saveTransFlow(transFlowBo);
        });
        return "success";
    }
}
